import request from './request'
import * as api from '@/common/api.js';

const accountInfo = uni.getAccountInfoSync()
const appId = accountInfo.miniProgram.appId;


function wxLogin() {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success: (res) => {
				// console.log(res.code);
				resolve(res)
			},
			fail: (res) => {
				reject(res)
			}
		})
	})
}

function pcLogin(code) {
	if (code) {
		return pcLoginByCode(code)
	} else {
		const currUser = uni.getStorageSync('currUser') || {}
		if (currUser.openId) {
			return pcLoginByOpenId(currUser.openId);
		} else {
			return wxLogin().then((loginRes) => {
				return pcLoginByCode(loginRes.code)
			})
		}
	}
}

function pcLoginByOpenId(openId) {
	return request({
		url: "/system/wx/loginByOpenId",
		method: "POST",
		params: {
			appId: appId,
			openId: openId
		}
	}).then((res) => {
		let user = res.data;
		// console.log("openId " + openId, user)

		uni.setStorageSync('token', 'Bearer ' + user.token);
		uni.setStorageSync('currUser', user);
		return user;
	}).catch(() => {
		uni.removeStorageSync('currUser')
	})
}

function pcLoginByCode(code) {
	return request({
		// url: "/weixin/api/login",
		url: "/system/wx/loginByJsCode",
		method: "POST",
		params: {
			appId: appId,
			jsCode: code
		}
	}).then((res) => {
		let user = res.data
		// console.log("code: " + code, user)
		// getNowOpenId()
		uni.setStorageSync('token', 'Bearer ' + user.token);
		uni.setStorageSync('currUser', user);
		return user;
	}).catch((err) => {
		uni.removeStorageSync('currUser')
	})
}

function getCurrUser(isAuto) {
	return request({
		url: "/system/wx/getUserInfo",
		method: "GET",
		opts: {
			isAuto: isAuto
		}
	}).then((res) => {
		let user = res.data;
		uni.setStorageSync('currUser', user);
		return user
	})
}

function getWxUser() {
	return new Promise((resolve, reject) => {
		const currUser = uni.getStorageSync('currUser');
		// getNowOpenId()
		const nowOpenId = uni.getStorageSync('nowOpenId');
		uni.getUserProfile({
			desc: '用于完善用户信息',
			success: function(infoRes) {
				console.log(infoRes)

				request({
					url: `/system/wx/updateWxUser?openId=${nowOpenId}`,
					method: "POST",
					params: {
						appId: appId,
						openId: nowOpenId,
						userId: currUser.id,
						encryptedData: infoRes.encryptedData,
						errMsg: infoRes.errMsg,
						iv: infoRes.iv,
						rawData: infoRes.rawData,
						signature: infoRes.signature
					}
				}).then((res) => {
					let user = res.data;
					uni.setStorageSync('currUser', user);
					resolve(user);
				}).catch(() => {
					reject()
				})
			},
			fail: (res) => {
				reject(res)
			}
		});
	});
}

function getWxUserPhone(phoneRes) {
	// console.log(phoneRes)

	const currUser = uni.getStorageSync('currUser');
	// getNowOpenId()
	const nowOpenId = uni.getStorageSync('nowOpenId');
	return request({
		url: `/system/wx/updateMobile?openId=${nowOpenId}`,
		method: "POST",
		params: {
			appId: appId,
			userId: currUser.id,
			encryptedData: phoneRes.encryptedData,
			errMsg: phoneRes.errMsg,
			iv: phoneRes.iv,
			rawData: phoneRes.rawData,
			signature: phoneRes.signature
		}
	}).then((res) => {
		let user = res.data;
		// uni.setStorageSync('token', 'Bearer '+ user.token);
		uni.setStorageSync('token', user.token);
		uni.setStorageSync('currUser', user);
		return user
	})
}

function checkUserAuth(path) {
	const currUser = uni.getStorageSync('currUser')
	if (currUser.phonenumber) {
		// if (currUser.nickName) {
		return true
	} else {
		uni.navigateTo({
			url: '/pages/index/start?path=' + encodeURIComponent(path)
		})
		return false;
	}
}

function getNowOpenId() {
	console.log('getNowOpenId')
	return request({
		url: `/system/user/getMyOpenId/${appId}`,
		method: 'get'
	}).then((res) => {
		uni.setStorageSync('nowOpenId', res.msg)
	})
}

function initData() {
	console.log('initData')

	const currUser = uni.getStorageSync('currUser');
	// console.log(currUser)
	return Promise.all([api.getVenue(), api.getOwnMemberInfo()]).then(res => {
		let ven = res[0].data;
		let men = res[1]?.data;

const app = getApp();

		if (ven.venuePic) {
			ven.venuePicArr = ven.venuePic.split(',');
		}
		if (ven.businessPeriod) {
			ven.startBus = ven.businessPeriod.split(',')[0];
			ven.endBus = ven.businessPeriod.split(',')[1];
		}
		ven.latitude = ven.lal.split(',')[0];
		ven.longitude = ven.lal.split(',')[1];

		app.globalData.venue = ven;
		app.globalData.isVip = men?.isVip;
		// app.globalData.relateProjectId = men.info.relateProjectId;
		app.globalData.relateProjectIdList = men?.info?.relateProjectIdList;
		app.globalData.relateVenueProjectIdList = men?.info?.relateVenueProjectIdList;

		app.globalData.venueConfig = {
			normalOverDay: ven.resSiteConfig?.normalOrderNum,
			normalPeriodStart: ven.resSiteConfig?.normalOrderPeriod.split(',')[0],
			normalPeriodEnd: ven.resSiteConfig?.normalOrderPeriod.split(',')[1]
		};
		if (men?.isVip) {
			app.globalData.venueConfig.memberOverDay = ven.resSiteConfig?.memberOrderNum;
			app.globalData.venueConfig.memberPeriodStart = ven.resSiteConfig?.memberOrderPeriod.split(',')[0];
			app.globalData.venueConfig.memberPeriodEnd = ven.resSiteConfig?.memberOrderPeriod.split(',')[1];
		}
	});
}

export {
	getNowOpenId,
	wxLogin,
	pcLogin,
	getCurrUser,
	getWxUser,
	getWxUserPhone,
	checkUserAuth,
	initData
}